using System;
using System.Collections.Generic;

namespace Servlets.Api
{
	/// <summary>
	/// Represents a Map of cookies.
	/// Cookies are indexed by a name. You can use the indexing operator[] to get the value of a cookie by a given key
	/// </summary>
	public class Cookies
	{
		private Dictionary<string, Cookie> cookies = new Dictionary<string, Cookie>();
		
		public Cookies () {}
		
		/// <summary>
		/// Creates a Cookies object from a collection of Cookie objects.
		/// </summary>
		/// <param name="c">
		/// A <see cref="IEnumerable<Cookie>"/>
		/// </param>
		public Cookies (IEnumerable<Cookie> c)
		{
			foreach(Cookie cookie in c) {
				cookies[cookie.Name] = cookie;
			}
		}
		
		/// <summary>
		/// Gets a <see cref="Servlets.Cookie"/>'s value with the given name. Throws an <see cref="Servlets.Exceptions.InvalidKeyException"/> if no <see cref="Servlets.Cookie"/> with the given name exists
		/// </summary>
		/// <param name="key">
		/// A <see cref="System.String"/>
		/// </param>
		public string this [string name] {
			get {
				return this.Get(name).Value;
			}
		}
		
		/// <summary>
		/// Gets a <see cref="Servlets.Cookie"/> with the given name. Throws an <see cref="Servlets.Exceptions.InvalidKeyException"/> if no <see cref="Servlets.Cookie"/> with the given name exists
		/// </summary>
		/// <param name="key">
		/// A <see cref="System.String"/>
		/// </param>
		public Cookie Get(string key) {
			Cookie c = this.TryGet(key);
			if(c == null)
				throw new Exceptions.InvalidKeyException(key);
			return c;
		}
		
		/// <summary>
		/// Gets a <see cref="Servlets.Cookie"/> with the given name. Returns null if no <see cref="Servlets.Cookie"/> with the given name exists
		/// </summary>
		/// <param name="key">
		/// A <see cref="System.String"/>
		/// </param>
		public Cookie TryGet(string key) {
			if(cookies.ContainsKey(key)) {
				return cookies[key];
			}
			
			return null;
		}
	}
}

